#include "function.h"
#include <cstring>
#include <vector>
#include <string>
using namespace std;
#include<json-c/json.h>
/* 构造函数 */
Function::Function(const StdTcpSocketPtr & clientInfo)
{
    m_clientInfo = clientInfo;
    /*todo ...*/
    m_sqliteDB.connectDB("./test2.db");
}

/* 析构函数 */
Function::~Function()
{

}

void Function::handleRegisterInfo(const string & msg)
{
    cout<<"handleRegisterInfo:"<<msg<<endl;

    const char *username = NULL;
    const char *passwd = NULL;
    json_object * jsonObj =  json_tokener_parse(msg.c_str());

    if(jsonObj != NULL)
    {
        //2.根据key得到value
        username = json_object_get_string( json_object_object_get(jsonObj,"username"));
        passwd = json_object_get_string( json_object_object_get(jsonObj,"passwd"));
    }
    //构建json字符串
    //1.创建json对象
    json_object * resObj = json_object_new_object();
    //2.设置<key:value>
    json_object_object_add(resObj,"type",json_object_new_int(REGISTER));
    if(userIsExist(username) == true)
    {
        json_object_object_add(resObj,"result",json_object_new_string("failed"));
        json_object_object_add(resObj,"reason",json_object_new_string("用户已存在"));
    }
    else
    {
        saveUserInfo(username,passwd);
        json_object_object_add(resObj,"result",json_object_new_string("success"));
    }

    //将json对象转成json字符串
    const char *resStr =  json_object_to_json_string(resObj);
    m_clientInfo->sendMessage(resStr);
}

void Function::handleLoginInfo(const string & msg)
{
    cout<<"handleLoginInfo:"<<msg<<endl;

    const char *username = NULL;
    const char *passwd = NULL;
    json_object * jsonObj =  json_tokener_parse(msg.c_str());

    if(jsonObj != NULL)
    {
        //2.根据key得到value
        username = json_object_get_string( json_object_object_get(jsonObj,"username"));
        passwd = json_object_get_string( json_object_object_get(jsonObj,"passwd"));
    }

    //构建json字符串
    //1.创建json对象
    json_object * resObj = json_object_new_object();
    //2.设置<key:value>
    json_object_object_add(resObj,"type",json_object_new_int(LOGIN));
    if(userIsExist(username) == false)
    {
        json_object_object_add(resObj,"result",json_object_new_string("failed"));
        json_object_object_add(resObj,"reason",json_object_new_string("用户不存在"));
    }
    else 
    {
        if(userIsMatchPasswd(username,passwd) == false)
        {
            json_object_object_add(resObj,"result",json_object_new_string("failed"));
            json_object_object_add(resObj,"reason",json_object_new_string("密码错误"));
        }
        else
        {
            json_object_object_add(resObj,"result",json_object_new_string("success"));
        }
    }
   
   //将json对象转成json字符串
    const char *resStr =  json_object_to_json_string(resObj);
    cout<< "resStr:"<<resStr<<endl;
    m_clientInfo->sendMessage(resStr);
}
//处理在线歌曲
void Function::handleOnlineMusicInfo(const string &msg)
{
    cout<<"handleOnlineMusicInfo:"<<msg<<endl;

    const char *musicname = NULL;
    json_object * jsonObj =  json_tokener_parse(msg.c_str());

    if(jsonObj != NULL)
    {
        //2.根据key得到value
        musicname = json_object_get_string( json_object_object_get(jsonObj,"musicname"));
    }

    //构建json字符串
    //1.创建json对象  device not open
    json_object * resObj = json_object_new_object();
    //2.设置<key:value>
    json_object_object_add(resObj,"type",json_object_new_int(ONLINEMUSIC));

    string musicFilePath = "/home/259ClassBasic/262班/OperationSystem/computerNetwork/Server/musicList/" + string(musicname) + ".mp3";
    std::cout<<"musicname:"<<string(musicname)<<endl;
    string musicData = readMusicFile(musicFilePath);
    cout<<"size:"<<musicData.size() <<endl;
    if(!musicData.empty())
    {   
        string encodeMusicData = base64_encode(reinterpret_cast<const unsigned char*>(musicData.c_str()),musicData.size());
        json_object_object_add(resObj,"musicname",json_object_new_string(musicname));
        json_object_object_add(resObj,"musiccontent",json_object_new_string(encodeMusicData.c_str()));

        // 构建歌词文件路径（假设歌词文件扩展名为 .lrc）
        string lyricsFilePath = "/home/259ClassBasic/262班/OperationSystem/computerNetwork/Server/musicList/" + string(musicname) + ".lrc";
        string lyricsData = readMusicFile(lyricsFilePath);  // 假设 readMusicFile 也适用于读取歌词文件
        cout << "lyrics size:" << lyricsData.size() << endl;

        if (!lyricsData.empty())
        {
            // 将歌词文件编码为 Base64
            string encodeLyricsData = base64_encode(reinterpret_cast<const unsigned char *>(lyricsData.c_str()), lyricsData.size());
            json_object_object_add(resObj, "lyricscontent", json_object_new_string(encodeLyricsData.c_str()));
        }
        // 处理专辑图片文件
        string albumImagePath = "/home/259ClassBasic/262班/OperationSystem/computerNetwork/Server/musicList/" + string(musicname) + ".png"; // 假设专辑图片文件为 .jpg
        string albumImageData = readMusicFile(albumImagePath);
        // std::cout<<"albumImageData"<<albumImageData;
        if (albumImageData.empty())
        {
            // 如果没有找到 .jpg 文件，可以尝试查找 .png 文件
            albumImagePath = "/home/259ClassBasic/262班/OperationSystem/computerNetwork/Server/musicList/" + string(musicname) + ".jpg";
            albumImageData = readMusicFile(albumImagePath);
        }

        if (!albumImageData.empty())
        {
            string encodeAlbumImageData = base64_encode(reinterpret_cast<const unsigned char *>(albumImageData.c_str()), albumImageData.size());
            json_object_object_add(resObj, "albumimage", json_object_new_string(encodeAlbumImageData.c_str()));
        }
    }
   
   //将json对象转成json字符串
    const char *resStr =  json_object_to_json_string(resObj);
    // cout<< "resStr:"<<resStr<<endl;
    m_clientInfo->sendMessage(resStr);
}

// 提取 .mp3 文件的元数据
std::string extractMetadata(const std::string &filePath)
{
    TagLib::FileRef file(filePath.c_str());

    if (!file.isNull() && file.tag())
    {
        TagLib::Tag *tag = file.tag();
        TagLib::AudioProperties *properties = file.audioProperties();

        std::string title = tag->title().to8Bit(true);
        std::string artist = tag->artist().to8Bit(true);
        int durationSec = properties ? properties->length() : 0;
        
        // 将时长从秒转换为分钟:秒格式
        int minutes = durationSec / 60;
        int seconds = durationSec % 60;

        std::ostringstream oss;
        oss << title << " - " << artist << " ("
            << std::setfill('0') << std::setw(2) << minutes << ":"
            << std::setfill('0') << std::setw(2) << seconds << ")";

        return oss.str();
    }
    else
    {
        return "Metadata not available";
    }
}

//处理在线歌曲歌单
void Function::handleOnlinesongsInfo(const string &msg)
{
    cout << "handleOnlineMusicInfo: " << msg << endl;

    // 指定音乐文件夹的路径
    const std::string musicDirectory = "/home/259ClassBasic/262班/OperationSystem/computerNetwork/Server/musicList/";
    
    // 创建一个 JSON 数组来存放所有音乐的元数据
    json_object *resArray = json_object_new_array();

    // 遍历目录中的所有文件
    for (const auto &entry : std::filesystem::directory_iterator(musicDirectory))
    {
        // 只处理 .mp3 文件
        if (entry.is_regular_file() && entry.path().extension() == ".mp3")
        {
            std::string musicFilePath = entry.path().string();
            std::string musicname = entry.path().stem().string(); // 获取不带扩展名的文件名
            
            std::cout << "Processing file: " << musicname << endl;

            // 提取音乐文件的元数据（例如，歌曲名称、艺术家、专辑等）
            std::string metadata = extractMetadata(musicFilePath);

            // 为该文件创建 JSON 对象
            json_object *fileObj = json_object_new_object();
            json_object_object_add(fileObj, "musicname", json_object_new_string(musicname.c_str()));
            json_object_object_add(fileObj, "metadata", json_object_new_string(metadata.c_str()));

            // 将文件对象添加到 JSON 数组中
            json_object_array_add(resArray, fileObj);
        }
    }

    // 创建一个最终的 JSON 对象，包含 type 和 songs 数组
    json_object *resObj = json_object_new_object();
    json_object_object_add(resObj, "type", json_object_new_int(ONLINESONGS));
    json_object_object_add(resObj, "songs", resArray);  // 将数组添加到对象中

    // 将 JSON 对象转换为字符串并发送
    const char *resStr = json_object_to_json_string(resObj);
    // cout << "resStr: " << resStr << endl;
    m_clientInfo->sendMessage(resStr);

    // 释放 JSON 对象
    json_object_put(resObj);
}

//下载歌曲
void Function::handledownloadMusicInfo(const string &msg)
{
    cout<<"handleOnlineMusicInfo:"<<msg<<endl;

    const char *musicname = NULL;
    json_object * jsonObj =  json_tokener_parse(msg.c_str());

    if(jsonObj != NULL)
    {
        //2.根据key得到value
        musicname = json_object_get_string( json_object_object_get(jsonObj,"musicname"));
    }

    //构建json字符串
    //1.创建json对象  device not open
    json_object * resObj = json_object_new_object();
    //2.设置<key:value>
    json_object_object_add(resObj,"type",json_object_new_int(DOWNLOADMUSIC));

    string musicFilePath = "/home/259ClassBasic/262班/OperationSystem/computerNetwork/Server/musicList/" + string(musicname) + ".mp3";
    std::cout<<"musicname:"<<string(musicname)<<endl;
    string musicData = readMusicFile(musicFilePath);
    cout<<"size:"<<musicData.size() <<endl;
    if(!musicData.empty())
    {   
        string encodeMusicData = base64_encode(reinterpret_cast<const unsigned char*>(musicData.c_str()),musicData.size());
        json_object_object_add(resObj,"musicname",json_object_new_string(musicname));
        json_object_object_add(resObj,"musiccontent",json_object_new_string(encodeMusicData.c_str()));

        // 构建歌词文件路径（假设歌词文件扩展名为 .lrc）
        string lyricsFilePath = "/home/259ClassBasic/262班/OperationSystem/computerNetwork/Server/musicList/" + string(musicname) + ".lrc";
        string lyricsData = readMusicFile(lyricsFilePath);  // 假设 readMusicFile 也适用于读取歌词文件
        cout << "lyrics size:" << lyricsData.size() << endl;

        if (!lyricsData.empty())
        {
            // 将歌词文件编码为 Base64
            string encodeLyricsData = base64_encode(reinterpret_cast<const unsigned char *>(lyricsData.c_str()), lyricsData.size());
            json_object_object_add(resObj, "lyricscontent", json_object_new_string(encodeLyricsData.c_str()));
        }
        // 处理专辑图片文件
        string albumImagePath = "/home/259ClassBasic/262班/OperationSystem/computerNetwork/Server/musicList/" + string(musicname) + ".png"; // 假设专辑图片文件为 .jpg
        string albumImageData = readMusicFile(albumImagePath);
        // std::cout<<"albumImageData"<<albumImageData;
        if (albumImageData.empty())
        {
            // 如果没有找到 .jpg 文件，可以尝试查找 .png 文件
            albumImagePath = "/home/259ClassBasic/262班/OperationSystem/computerNetwork/Server/musicList/" + string(musicname) + ".jpg";
            albumImageData = readMusicFile(albumImagePath);
        }

        if (!albumImageData.empty())
        {
            string encodeAlbumImageData = base64_encode(reinterpret_cast<const unsigned char *>(albumImageData.c_str()), albumImageData.size());
            json_object_object_add(resObj, "albumimage", json_object_new_string(encodeAlbumImageData.c_str()));
        }
    }
   
   //将json对象转成json字符串
    const char *resStr =  json_object_to_json_string(resObj);
    // cout<< "resStr:"<<resStr<<endl;
    m_clientInfo->sendMessage(resStr);
}
/* 判断用户名是否存在 */
bool Function::userIsExist(const char * username)
{   
    /* todo... */
    string sql = "select count(1) from userInfo where username = '%s';";
    char requestSql[128] = {0};
    sprintf(requestSql,sql.c_str(),username);
    vector<vector<string>> res =  m_sqliteDB.query(requestSql);
    if(res[0][0] == "0")
    {
        return false;
    }
    return true; 
}
//保存用户信息
bool Function:: saveUserInfo(const char * username, const char *  passwd)
{
    string sql = "insert into userInfo (username,passwd) values ('%s','%s');";
    char requestSql[128] = {0};
    sprintf(requestSql,sql.c_str(),username,passwd);
    if(m_sqliteDB.execute(requestSql) == false)
    {
        cout<<"saveUserInfo error"<<__FILE__<<":"<<__LINE__<<endl;
        return false;
    }
    return true;
}
/* 用户名和密码是否匹配 */
bool Function::userIsMatchPasswd(const char * username, const char *  passwd)
{
    /* todo... */
    string sql = "select count(1) from userInfo where username = '%s' and passwd = '%s';";
    char requestSql[128] = {0};
    sprintf(requestSql,sql.c_str(),username,passwd);
    vector<vector<string>> res =  m_sqliteDB.query(requestSql);
    if(res[0][0] == "0")
    {
        return false;
    }
    return true;
}

/* 用户是否已经登陆/在线 */
bool Function::userIsOnlined(const char * username)
{
    /* todo... */
    return true;
}

string Function::readMusicFile(const string &filePath)
{
    ifstream file(filePath,ios::in | ios::binary);
    if(file)
    {
        file.seekg(0,ios::end);
        size_t size = file.tellg();
        file.seekg(0,ios::beg);

        string buffer(size,'\0');
        file.read(&buffer[0],size);
        file.close();

        return buffer;
    }
    else
    {
        return "";
    }
}

void Function::handleAddFriendInfo(const string &msg)
{
    
}


